package cn.ittgh.utils;

import org.springframework.stereotype.Component;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;

@Component
public class MD5Util {


	// 加盐的MD5加密方法
	public static String md5WithSalt(String input, String salt) {

		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(salt.getBytes());
			byte[] raw = md.digest(input.getBytes());
			return bytesToHex(raw);
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException("MD5 algorithm not available", e);
		}
	}

	// 不加盐的MD5加密方法
	public static String md5(String input) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			byte[] raw = md.digest(input.getBytes());
			return bytesToHex(raw);
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException("MD5 algorithm not available", e);
		}
	}

	// 将字节数组转换为十六进制字符串
	private static String bytesToHex(byte[] bytes) {
		StringBuilder hexString = new StringBuilder();
		for (byte b : bytes) {
			String hex = Integer.toHexString(0xff & b);
			if (hex.length() == 1) {
				hexString.append('0');
			}
			hexString.append(hex);
		}
		return hexString.toString();
	}

	// 验证两个字符串的MD5哈希值是否相等
	public static boolean verifyMD5(String input, String md5Hash) {
		return md5(input).equals(md5Hash);
	}

	// 验证加盐后的两个字符串的MD5哈希值是否相等
	public static boolean verifyMD5(String input, String md5Hash, String salt) {
		return md5WithSalt(input, salt).equals(md5Hash);
	}

	// 生成随机盐值
	public static String generateSalt(int length) {
		SecureRandom random = new SecureRandom();
		byte[] salt = new byte[length];
		random.nextBytes(salt);
		return Base64.getEncoder().encodeToString(salt);
	}


}